%load_ext pretty_jupyter

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

sns.set_theme()
%%jmd

## Algorithm
[//]: <> (-.- tabset tabset-pills)

Sometimes we want to create tabsets dynamically, meaning we want to generate them based on a code.
Pretty Jupyter supports this by using Jinja Markdown cells.

We first create all image tags and then we print them using Jinja Markdown.

Algorithm

Sometimes we want to create tabsets dynamically, meaning we want to generate them based on a code. Pretty Jupyter supports this by using Jinja Markdown cells.

We first create all image tags and then we print them using Jinja Markdown.

import base64
from io import BytesIO

# create dataframe
data = pd.DataFrame({"a": [1, 2, 3, 4], "b": [4, 3, 2, 1], "c": [1, 4, 2, 3]})

img_tags = {}

def get_img_tag(fig):
    """Function that creates image tag out of figure."""
    img_format = r"<img src='data:image/png;base64,{encoded}' />"
    
    tmpfile = BytesIO()
    fig.savefig(tmpfile, format="png")
    plt.close()

    encoded = img_format.format(encoded=base64.b64encode(tmpfile.getvalue()).decode('utf-8'))
    return encoded

# create image tags in a for loop
for col in data.columns:
    ax = sns.lineplot(x=np.arange(len(data)), y=data[col], marker="o")
    ax.set(title=f"Plot for column '{col}'", ylabel=col)
    img_tags[col] = get_img_tag(ax.figure)
%%jmd

{% for col, img in img_tags.items() %}

### Tabset for column {{ col }}

Content for column {{ col }}.

{{ img }}

{% endfor %}

Tabset for column a

Content for column a.

Tabset for column b

Content for column b.

Tabset for column c

Content for column c.

Each Jinja Markdown cell is internally ran through Jinja templating framework. To read more about Jinja, check out its documentation.